package com.yidianyanglao.shop.controller;

import com.alibaba.druid.support.json.JSONParser;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yidianyanglao.core.bean.RetBean;
import com.yidianyanglao.core.enums.Code;
import com.yidianyanglao.core.exception.CustomException;
import com.yidianyanglao.shop.bean.Order;
import com.yidianyanglao.shop.bean.OrderProduct;
import com.yidianyanglao.shop.bean.Shop;
import com.yidianyanglao.shop.mapper.ShopMapper;
import com.yidianyanglao.user.mapper.UserMapper;
import com.yidianyanglao.userData.bean.ShopBean;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * describe :   ------      ------
 * author  :        lf
 * time on  :   ${DAte}  16:22.
 * ----------------------------------------------------
 */
@Controller
public class ShopController {

    @Resource
    private ShopMapper sm;
    @Resource
    private UserMapper userMapper;
    /**
     * shop列表
     * @param request
     * @param pageNum
     * @param shopname
     * @param x
     * @param y
     * @return
     */
    @RequestMapping("/shop/shopList.json")
    @ResponseBody
    public RetBean shopList(HttpServletRequest request,String pageNum,String shopname,String x,String y,String province,String city,String area,String industrytype){
        String str = pageNum+","+x+","+y+","+province+","+city;
        if(!checkParameter(str)){
            throw new CustomException(Code.ERROR, "参数"+str+"均不能为空");
        }
        int begin = checkPageNum(pageNum);
        if(!checkParameter(shopname)){
            shopname = "";
        }
        if(!checkParameter(area)){
            area = "";
        }
        String shopName_ = "%"+shopname+"%";
        String area_ = "%"+area+"%";

        List<ShopBean> list = null;
        if(StringUtils.isEmpty(industrytype)){
            list = sm.getShopList(begin,shopName_,province,city,area_);
        }else{
            list = sm.getShopListByIndustry(begin,shopName_,province,city,area_,industrytype);
        }
        for(ShopBean shop:list){
            String shopX = shop.getX();
            String shopY = shop.getY();
            if(!(shopX==null||shopX.equals("")||shopX.equals(null)||shopY==null||shopY.equals("")||shopY.equals(null))){
                BigDecimal x_ = new BigDecimal(x);
                BigDecimal y_ = new BigDecimal(y);
                BigDecimal sx = new BigDecimal(shopX);
                BigDecimal sy = new BigDecimal(shopY);
                double distance = GetDistance(x_.doubleValue(),y_.doubleValue(),sx.doubleValue(),sy.doubleValue());
                shop.setDistance(String.valueOf(distance));
            }
        }
        //distance排序
        if(list.size()>1){
            Collections.sort(list,new ShopCom());
        }
        return new RetBean(Code.SUCCESS,"请求成功",list);
    }

    private static final double EARTH_RADIUS = 6378137;

    private static double rad(double d){
              return d * Math.PI / 180.0;
    }

    /* x、y获取距离(单位: m) */
    public static double GetDistance(double lng1, double lat1, double lng2, double lat2) {
        double radLat1 = rad(lat1);
        double radLat2 = rad(lat2);
        double a = radLat1 - radLat2;
        double b = rad(lng1) - rad(lng2);
        double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a/2),2) +
                Math.cos(radLat1)*Math.cos(radLat2)*Math.pow(Math.sin(b/2),2)));
        s = s * EARTH_RADIUS;
        s = Math.round(s * 10000) / 10000;
        return s;
    }

    public boolean isPositiveInteger(String pageNum) {
        return isMatch("^\\+{0,1}[1-9]\\d*", pageNum);
    }

    private boolean isMatch(String regex, String pageNum){
        if (pageNum == null || pageNum.trim().equals("")) {
            return false;
        }
        Pattern pattern = Pattern.compile(regex);
        Matcher isNum = pattern.matcher(pageNum);
        return isNum.matches();
    }

    public int checkPageNum(String pageNum){
        int begin = 0;
        if(!isPositiveInteger(pageNum)){
            throw new CustomException(Code.ERROR, "pageNum只能是正整数");
        }else{
            if(Integer.valueOf(pageNum)>1){
                begin = (Integer.valueOf(pageNum) - 1)* 10;
            }
            return begin;
        }
    }

    public boolean checkParameter(String str){
        boolean b = true;
        if(str == null){
            return  false;
        }
        String [] s = str.split(",");
        for(int i=0;i<s.length;i++){
            if(s[i]==null || s[i].equals("") || s[i].equals("null")){
                b = false;
            }
        }
        return b;
    }
     /* ShopBean比较器 */
    public class ShopCom implements Comparator<ShopBean> {

        @Override
        public int compare(ShopBean s1, ShopBean s2) {

            int i=0;
            if(s1.getDistance()!=null && s2.getDistance()!=null){
                i = new Double(s1.getDistance()).compareTo(new Double(s2.getDistance()));
            }
            return i;
        }
    }

    /**
     * 根据商户id查看商户详情
     * @param request
     * @param response
     * @param shopid
     * @return
     */
    @RequestMapping("/shop/getShopInfo.json")
    @ResponseBody
    public RetBean getShopInfo(HttpServletRequest request,HttpServletResponse response,int shopid){

        Shop shop = sm.getShopById(shopid);
        return new RetBean(Code.SUCCESS,"获取商户详情",shop);

    }


    /**
     * 对外提供下单接口
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/shop/addOrder.json")
    @ResponseBody
    public RetBean addOrder(HttpServletRequest request, HttpServletResponse response){
        Order order = new Order();

        order.setConsumptionId(1);
        order.setConsumptionName("haha");
        order.setConsumptionMobile("18357116932");

        order.setShopId(1);
        order.setShopName("shopnanana");

        order.setSeriesId(1);
        order.setSeriesName("12系列");

        order.setBusinessId(1);
        order.setBusinessName("哈哈哈");

        order.setCreatedate("2016-01-01 00:00:00");
        order.setAmountvalue(100.10);

        order.setOrdernumber("10010");
        order.setResource("一点公益");

        order.setOrderstate(0);
        order.setConsumptionCertificate("http://www.baidu.com");

        OrderProduct oa = new OrderProduct("哇哈哈","001","123456",10,"200");
        OrderProduct ob = new OrderProduct("哇哈哈","002","123456",10,"200");
        OrderProduct oc = new OrderProduct("哇哈哈","003","123456",10,"200");
        List<OrderProduct> list = new ArrayList<OrderProduct>();
        list.add(oa);
        list.add(ob);
        list.add(oc);


        JSONObject json = new JSONObject();
        json.put("order",order);
        json.put("list",list);
        String result = json.toJSONString();
        System.out.println("result:"+result);

        try{

            json = JSON.parseObject(result);
//            Map<String,Object> obj = (Map)json.get("order");
//            Set<String> set = obj.keySet();
//            for (String s:set) {
//                System.out.println(s+","+obj.get(s));
//            }

            Order o = JSON.parseObject(json.getString("order"),Order.class);
            List<OrderProduct> l = JSON.parseArray(json.getString("list"),OrderProduct.class);
            System.out.println(o.toString());
            for (int i = 0; i < l.size(); i++) {
                System.out.println(l.get(i).toString());
            }

        }catch (Exception e){
            System.out.println(e.toString());
        }

        return new RetBean(Code.SUCCESS,"下单成功",null);
    }



}
